var app = getApp();
var webhost = app.globalData.webhost;
var upLoadHost = app.globalData.upLoadHost;
var util = require('../../utils/date.js');

Page({
  data: {
    id: '',
    planData: {},
    taskData: {},
    doDate: '',
    outDate: '',
    happenDate: '',
    index: 0,
    imgs: [],
    abnormaTypeList: [],
    abnormaTypeCodeList: []
  },

  //修改反馈日期
  bindDate1: function(e) {
    this.setData({
      doDate: e.detail.value,
    })
  },

  //修改出车日期
  bindDate2: function(e) {
    this.setData({
      outDate: e.detail.value,
    })
  },

  //修改发生日期
  bindDate3: function(e) {
    this.setData({
      happenDate: e.detail.value,
    })
  },

  bindStatus: function(e) {
    var that = this;
    that.setData({
      index: +e.detail.value
    })
  },

  inputRemarks: function(e) {
    var that = this;
    that.setData({
      exceptionRemarks: e.detail.value
    })
  },

  // 上传图片
  addPhoto: function(e) {
    var that = this;
    var upPicData = that.data.upPicData
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths;
        var imgs = that.data.imgs;
        var url = upLoadHost;
        if (tempFilePaths) {
          for (var i = 0; i < tempFilePaths.length; i++) {
            var now = new Date();
            var filename = that.data.upPicData.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", now);
            imgs.push(url + '/' + filename);
            wx.uploadFile({
              url: url,
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                name: tempFilePaths[i],
                key: filename,
                policy: that.data.upPicData.policy,
                OSSAccessKeyId: that.data.upPicData.accessid,
                success_action_status: "200",
                signature: that.data.upPicData.signature
              },
              success: function(res) {
                var data = res.data;
                if (imgs.length <= 10) {
                  that.setData({
                    imgs: imgs
                  })
                } else {
                  wx.showModal({
                    title: '提示',
                    showCancel: false,
                    confirmColor: '#118EDE',
                    content: '图片数量不能超过10张',
                    success: function(res) {
                      if (res.confirm) {
                        imgs = imgs.slice(0, 10);
                        that.setData({
                          imgs: imgs
                        })
                      }
                    }
                  })
                }
              }
            })
          }
        }
      }
    })
  },

  upLoadImg(tempFilePaths, i) {
    var that = this;
    var upPicData = that.data.upPicData;
    wx.showLoading({
      title: '图片上传中',
    })
    var fileName = upPicData.dir + '/' + app.globalData.driverAccount + util.Format("yyyyMMddhhmmssS", new Date());
    var url = upLoadHost;
    var imgs = that.data.imgs;
    var item = {
      picturePath: url + '/' + fileName
    }
    wx.uploadFile({
      url: url,
      filePath: tempFilePaths[i],
      name: 'file',
      formData: {
        name: tempFilePaths[i],
        key: fileName,
        policy: upPicData.policy,
        OSSAccessKeyId: upPicData.accessid,
        success_action_status: "200",
        signature: upPicData.signature
      },
      success(res) {
        imgs.push(item);
        that.setData({
          imgs: imgs
        })
        i++;
        if (i < tempFilePaths.length) {
          that.upLoadImg(tempFilePaths, i);
        } else {
          wx.hideLoading();
        }
      },
      fail() {
        wx.showToast({
          title: '第' + i + '张图片上传失败',
          icon: 'none'
        })
      }
    })
  },

  picClick() {
    var that = this;
    if (!that.data.upPicData.accessid) {
      wx.showToast({
        title: '未获取上传权限',
        icon: 'none'
      })
      return false;
    }
    var count = 9;
    count = 9 - that.data.imgs.length;
    if (count <= 0) {
      wx.showToast({
        title: '最多上传9张图片',
        icon: 'none'
      })
      return false;
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        var tempFilePaths = res.tempFilePaths;
        if (tempFilePaths) {
          var i = 0;
          that.upLoadImg(tempFilePaths, i);
        }
      }
    })
  },

  // 删除图片
  deleteImg: function(e) {
    var imgs = this.data.imgs;
    var index = e.currentTarget.dataset.index;
    imgs.splice(index, 1);
    this.setData({
      imgs: imgs
    });
  },

  // 预览图片
  previewImg: function(e) {
    //获取当前图片的下标
    var index = e.currentTarget.dataset.index;
    //所有图片
    var imgs = this.data.imgs;
    var preImgs = [];
    for(var i =0;i<imgs.length;i++){
      preImgs[i] = imgs[i].picturePath;
    }
    wx.previewImage({
      //当前显示图片
      current: preImgs[index],
      //所有图片
      urls: preImgs
    })
  },

  //提交异常登记
  submit: function() {
    var that = this;
    var planData = app.globalData.plan;
    var taskData = app.globalData.task;
    var index = that.data.index;
    var abnormaTypeCodeList = that.data.abnormaTypeCodeList;
    var data = {
      exceptionFeedbackDate: that.data.doDate,
      exceptionAssociateNo: '',
      exceptionType: that.data.abnormaTypeCodeList[index],
      exceptionRemarks: that.data.exceptionRemarks,
      carId: planData.carId,
      exceptionStatus: '新建',
      n1: that.data.happenDate,
      n2: planData.planNo,
      n3: taskData.planTaskNo,
      n4: taskData.customerName,
      n5: planData.n4,
      n6: planData.n1,
    }
    if (planData.planId) {
      var parameters = [{
        String: {
          driverAccount: app.globalData.driverAccount,
          sessionid: app.globalData.sessionid,
          planId: planData.planId,
          taskCode: planData.taskCode,
          actionCode: 'EXCE',
          data: data,
          dataList: that.data.imgs
        }
      }]
    } else {
      var parameters = [{
        String: {
          driverAccount: app.globalData.driverAccount,
          sessionid: app.globalData.sessionid,
          planId: planData.planId,
          taskid: planData.taskid,
          taskCode: planData.taskCode,
          actionCode: 'EXCE ',
          data: data,
          dataList: that.data.imgs
        }
      }]
    }
    wx.request({
      url:webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'doExceptionEvent', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(parameters)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        if (code == '000000') {
          wx.showModal({
            title: '异常登记成功！',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function (res) {
              if (res.confirm) {
                var pages = getCurrentPages();
                pages[pages.length - 2].onPullDownRefresh();
                wx.navigateBack({});
              }
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmColor: '#118EDE',
            content: res.data.msg,
            success: function(res) {
              if (code == '003000') {
                if (res.confirm) {
                  wx.reLaunch({
                    url: '../login/login'
                  })
                }
              }
            }
          })
        }
      }
    })
  },

  restet:function(){
    var curDate = util.getFormatDate(new Date);
    this.setData({
      doDate: curDate,
      outDate: curDate,
      happenDate: curDate,
      index: 0,
      exceptionRemarks: '',
      imgs: []
    })
  },

  onLoad: function(options) {
    var that = this;

    var curDate = util.getFormatDate(new Date);

    that.setData({
      id: options.id || '',
      driverAccount: app.globalData.driverAccount,
      sessionid: app.globalData.sessionid,
      driverName: app.globalData.driverName,
      planData: app.globalData.plan,
      taskData: app.globalData.task,
      doDate: curDate,
      outDate: curDate,
      happenDate: curDate,
    });

    var parameters2 = [{
      String: {
        sessionid: app.globalData.sessionid
      }
    }]

    //拉取异常类型
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getCodeList', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: "[{ String: { 'codeListKey': 'tsp2_abnormaType' } }]"
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function(res) {
        var code = res.data.code;
        var abnormaTypeList = [];
        var abnormaTypeCodeList = [];
        if (code == '000000') {
          for (var i = 0; i < res.data.codeList.length; i++) {
            abnormaTypeList[i] = res.data.codeList[i].codeName
            abnormaTypeCodeList[i] = res.data.codeList[i].codeValue
          }
          that.setData({
            abnormaTypeList: abnormaTypeList,
            abnormaTypeCodeList: abnormaTypeCodeList
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
      }
    })

    //获取上传权限
    wx.request({
      url: webhost,
      data: {
        eap_username: "driver",
        eap_password: "Driver2018",
        boId: "tspdriver_tsp2DriverServiceBO_bo", //调用的bo
        methodName: 'getFileUploadPermission', //调用的具体方法
        returnType: "json", //返回参数类型
        parameters: JSON.stringify(parameters2)
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function({data}) {
        if (data && data.code == '000000') {
          var data = data.data;
          that.setData({
            upPicData: data
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        }
      }
    })
  },

  onShow: function() {

  },

  onPullDownRefresh: function() {

  },

  onReachBottom: function() {

  },

  onShareAppMessage: function() {

  }
})